package com.wdc.deliveryrobot.control;

import android.util.Log;

import com.sirui.selfstudysdk.main.SelfChassisState;
import com.wdc.deliveryrobot.event.Event;

import org.greenrobot.eventbus.EventBus;

/**
 * @Author: tianHuiDa
 * @Date: 2024/11/15
 * @Description: 数据监听
 */
public class DataController {

    private static DataController instance;

    private Thread thread;

    private EventBus eventBus;

    public SelfChassisState selfChassisState;

    private boolean isInit = false;


    private DataController(){
        selfChassisState = SelfChassisState.getInstance();
        isInit = selfChassisState.init("192.168.31.7:9090");
        startThread();
    }

    public static DataController getInstance(){
        if (instance == null){
            synchronized (DataController.class){
                if (instance == null){
                    instance = new DataController();
                }
            }
        }
        return instance;
    }


    private void startThread(){
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
               //循环获取数据
                while (isInit){
                    onResult(selfChassisState.getResult().toString(),1);

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });

        thread.start();  // 确保线程开始执行
    }

    private void onResult(String result,Integer type){
        if (type.equals(1)){
            //运行状态
            EventBus.getDefault().post(Event.getOnDataEvent(Integer.parseInt(result)));
        }

    }


    // 停止循环任务
    public void stop() {
        isInit = false;  // 设置标志位，停止循环
        thread.interrupt();  // 如果线程在等待（sleep），可以中断线程
    }

    // 取消注册 EventBus
    public void unregister() {
    }
}
